package jard.webshop.management;

import jard.webshop.nbp.SitePref;
import jard.webshop.util.Constants;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

/**
 *
 * @author CJP
 */
public class PreferencesManagement {

    private static EntityManagerFactory emf = null;

    public static void setEntityManagerFactory(EntityManagerFactory givenEmf) {
        emf = givenEmf;
    }
    private static PreferencesManagement prm = null;

    public static PreferencesManagement getInstance() {
        if (prm == null) {
            prm = new PreferencesManagement();
        }
        if(emf == null) {
            emf = Persistence.createEntityManagerFactory("jard_webshop_PU");
        }

        return prm;
    }

    private PreferencesManagement() {
    }

    public void addPreferences(SitePref pref) {
        System.out.println("in addPreferences, emf => " + emf);
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        System.out.println("em.contains(" + pref + ") => " + em.contains(pref));
        em.persist(pref);
        tx.commit();
    }

    public void savePreferences(SitePref pref) {
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        System.out.println("em.contains(" + pref + ") => " + em.contains(pref));
        em.merge(pref);
        tx.commit();
    }

    public void removePreferences(SitePref pref) {
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        System.out.println("em.contains(" + pref + ") => " + em.contains(pref));
        em.remove(em.merge(pref));
        tx.commit();
    }

    public List<SitePref> getPreferences() {
        EntityManager em = emf.createEntityManager();

        TypedQuery<SitePref> query = em.createNamedQuery(Constants.GET_ALL_PREFS, SitePref.class);
        try {
            List<SitePref> retVal = query.getResultList();
            return retVal;
        } catch (NoResultException e) {
            return new ArrayList<SitePref>();
        }
    }
    
}
